package com.shanjupay.merchant.controller;

import com.alibaba.fastjson.JSON;
import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.common.util.PhoneUtil;
import com.shanjupay.merchant.api.MerchantService;
import com.shanjupay.merchant.api.dto.MerchantDTO;
import com.shanjupay.merchant.common.util.SecurityUtil;
import com.shanjupay.merchant.convert.MerchantDetailConvert;
import com.shanjupay.merchant.convert.MerchantReisterConvert;
import com.shanjupay.merchant.service.FileService;
import com.shanjupay.merchant.service.SmsService;
import com.shanjupay.merchant.vo.MerchantDetailVo;
import com.shanjupay.merchant.vo.MerchantRegisterVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@Api(value = "商户平台-商户相关",tags = "商户平台应用的接口", description = "商户平台应用的接口")
public class MerchantController {

    @Reference
    private MerchantService merchantService ;

    @Autowired
    private FileService fileService;

    @Autowired
    private SmsService smsService;


    @ApiOperation("获取登陆用户的商户信息")
    @GetMapping(value = "/my/merchants")
    public MerchantDTO getMyMerchantInfo() {
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO merchantDTO = merchantService.queryMerchantById(merchantId);
        return merchantDTO;
    }

    @ApiOperation("商户资质申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantInfo",value = "商户认证资料",required = true, dataType = "MerchantDetailVo", paramType = "body")
    })
    @PostMapping("/my/merchants/save")
    public void  saveMerchant(@RequestBody MerchantDetailVo merchantInfo){
        // 解析token ,取出当前登陆商户的id
        Long merchantId = SecurityUtil.getMerchantId();

        log.info("获取的商户id：{}",merchantId);

        // VO 转换
        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.vo2dto(merchantInfo);

        merchantService.applyMerchant(merchantId,merchantDTO);
    }


    @ApiOperation(value = "根据id查询商户信息")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id",value = "主键id",required = true, dataType = "long")
    )
    @GetMapping("/merchants/{id}")
    public MerchantDTO queryMerchantById(@PathVariable("id") Long id){
        MerchantDTO merchantDTO = merchantService.queryById(id);
        return merchantDTO;
    }

    @ApiOperation(value = "测试")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = true, dataType = "string")
    })
    @PostMapping(value = "/hi")
    public String hi(String name){
        return "hi "+ name;
    }

    @ApiOperation("测试")
    @GetMapping(path = "/hello")
    public String hello(){
        return "hello ==> "+ " world";
    }


    @ApiOperation("获取手机验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "手机号" ,name = "phone",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping(path = "/sms")
    public String getSMSCode(@RequestParam(value = "phone")String phone){
        log.info("向手机号：{} 发送验证码",phone);
        // 向验证码服务请求发送验证码
        return smsService.sendMsg(phone);
    }

    @ApiOperation("注册商户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "注册信息" ,name = "merchantRegister",required = true,dataType = "MerchantRegisterVo",paramType = "body")
    })
    @PostMapping(path = "/merchants/register")
    public MerchantRegisterVo registerMerchant(@RequestBody MerchantRegisterVo merchantRegister){
        log.info("接收的参数为：{}", JSON.toJSONString(merchantRegister));

        // 校验参数的合法性
        if(merchantRegister == null) {
            throw new BusinessException(CommonErrorCode.E_100108);
        }

        // 手机号校验
        if(StringUtils.isBlank(merchantRegister.getMobile())){
            // 手机号为空
            throw new BusinessException(CommonErrorCode.E_100112);
        }
        // 手机号格式校验
        if(!PhoneUtil.isMatches(merchantRegister.getMobile())){
            throw new BusinessException(CommonErrorCode.E_100109);
        }

        // 校验验证码
        smsService.checkVerifiyCode(merchantRegister.getVerifiykey(),merchantRegister.getVerifiyCode());
        // 注册商户信息
        //MerchantDTO merchantDTO = new MerchantDTO();
        // 向dto 写入商户注册信息
        //merchantDTO.setMobile(merchantRegister.getMobile());
        //merchantDTO.setUsername(merchantRegister.getUsername());
        // 将 vo 转换成 dto
        MerchantDTO merchantDTO = MerchantReisterConvert.INSTANCE.vo2dto(merchantRegister);

        MerchantDTO merchant = merchantService.createMerchant(merchantDTO);

        MerchantRegisterVo merchantRegisterVo = MerchantReisterConvert.INSTANCE.dto2vo(merchant);
        log.info("注册成功返回的VO对象：{} " + JSON.toJSONString(merchantRegisterVo));
        return merchantRegister;
    }


    @ApiOperation("证件上传")
    @PostMapping("/upload")
    public String uploadFile(@ApiParam(value = "上传的文件" ,required = true) @RequestParam("file")MultipartFile file) throws IOException {

        // 调用fileService 上传文件
        // 生成的文件名称fileName，要保证他的唯一
        // 原始文件名称
        String originalFilename = file.getOriginalFilename();
        // 文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")-1);
        // 文件名称
        String fileName = UUID.randomUUID().toString()+suffix;
        // 上传文件
        String uploadFile = fileService.uploadFile(file.getBytes(), fileName);

        return uploadFile;
    }

}
